package cn.iocoder.yudao.module.alipay.didi.auth;

import org.apache.commons.codec.digest.DigestUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.TreeMap;

public class Auth {
    public static String genSign(TreeMap<String, Object> header, TreeMap<String, Object> body, String accessKey) throws Exception {
        TreeMap<String, Object> params = new TreeMap<>();
        for (String key : header.keySet()) {
            params.put(key, header.get(key));
        }
        for (String key : body.keySet()) {
            params.put(key, body.get(key));
        }

        StringBuilder str = new StringBuilder();
        for (String key : params.keySet()) {
            str.append("&").append(key).append("=").append(params.get(key));
        }
        str = new StringBuilder(str.toString().replaceFirst("&", ""));
        str = new StringBuilder(URLEncoder.encode(str.toString(), String.valueOf(StandardCharsets.UTF_8)));
        str.append(accessKey);
        str = new StringBuilder(DigestUtils.shaHex(str.toString().getBytes(StandardCharsets.UTF_8)));
        str = new StringBuilder(Base64.getEncoder().encodeToString(str.toString().getBytes(StandardCharsets.UTF_8)));
        str = new StringBuilder(URLEncoder.encode(str.toString(), String.valueOf(StandardCharsets.UTF_8)));
        return str.toString();
    }
}
